#include <iostream>
#include <fstream>
#include "ObjModelFile.h"

void ConvertToMdlFile( const ObjModelFile& objFile, MdlFile& mdlFile )
{	
	unsigned int count = objFile.vertexIndices.size();
	std::vector<float> unindexedverts;
	
	for (unsigned int i = 0; i < count; ++i)
	{
		const unsigned int& vertexindex = objFile.vertexIndices[i];
		const unsigned int& normalindex = objFile.nIndices[i];
		const unsigned int& uvindex = objFile.uvIndices[i];

		unindexedverts.push_back(objFile.vertices[vertexindex*3]);
		unindexedverts.push_back(objFile.vertices[vertexindex*3+1]);
		unindexedverts.push_back(objFile.vertices[vertexindex*3+2]);
		unindexedverts.push_back(objFile.normals[normalindex*3]);
		unindexedverts.push_back(objFile.normals[normalindex*3+1]);
		unindexedverts.push_back(objFile.normals[normalindex*3+2]);
		unindexedverts.push_back(objFile.uvs[uvindex*2]);
		unindexedverts.push_back(objFile.uvs[uvindex*2+1]);
	}

	mdlFile.meshes.resize(1);
	mdlFile.meshes[0].vertexCount = count;
	mdlFile.meshes[0].vertexData.resize(count * 32);
	memcpy(&(mdlFile.meshes[0].vertexData[0]), &(unindexedverts[0]), count * 32);
	mdlFile.meshes[0].parameters.push_back(Type(0, 3, 0x84C8));
	mdlFile.meshes[0].parameters.push_back(Type(12, 3, 0x84C9));
	mdlFile.meshes[0].parameters.push_back(Type(24, 2, 0x84C0));
}

bool LoadObjModelFile( const char* filename, ObjModelFile& model )
{
	int length = 0;

	std::ifstream file(filename, std::ios::binary);

	if(!file.is_open())
		return false;

	char header[256];
	float floatValue[3];
	unsigned int uintValue[9];

	while (!file.eof())
	{
		file >> header;

		if (strcmp(header, "v") == 0)						// vertex
		{
			for (int i = 0; i < 3; ++i)
			{
				file >> floatValue[i];
				model.vertices.push_back(floatValue[i]);
			}
		} else if (strcmp(header, "vt") == 0)				// texture
		{
			for (int i = 0; i < 2; ++i)
			{
				file >> floatValue[i];
				model.uvs.push_back(floatValue[i]);
			}
		} else if (strcmp(header, "vn") == 0)				// normal
		{
			for (int i = 0; i < 3; ++i)
			{
				file >> floatValue[i];
				model.normals.push_back(floatValue[i]);
			}
		} else if (strcmp(header, "f") == 0)				// face
		{
			for (int i = 0; i < 3; ++i)
			{
				char c;
				file >> uintValue[i*3];
				file >> c;
				file >> uintValue[i*3+1];
				file >> c;
				file >> uintValue[i*3+2];
			}
			model.vertexIndices.push_back(uintValue[0]-1);
			model.uvIndices.push_back(uintValue[1]-1);
			model.nIndices.push_back(uintValue[2]-1);
			model.vertexIndices.push_back(uintValue[3]-1);
			model.uvIndices.push_back(uintValue[4]-1);
			model.nIndices.push_back(uintValue[5]-1);
			model.vertexIndices.push_back(uintValue[6]-1);
			model.uvIndices.push_back(uintValue[7]-1);
			model.nIndices.push_back(uintValue[8]-1);
		}
	}
	return true;
}